//
//  CommentViewController.m
//  FoodList
//
//  Created by 王金晶 on 16/4/13.
//  Copyright © 2016年 王金晶. All rights reserved.
//

#import "CommentViewController.h"
#import "CommentModel.h"
#import "CommentTableViewCell.h"
@interface CommentViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property(nonatomic,strong)NSMutableArray *modelArray;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)UITextField *commentField;
@property(nonatomic,strong)UIView *keyview;
@end

@implementation CommentViewController
#pragma mark ---------试图将要出现 添加关注 关注键盘---------------
- (void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil]; // 键盘弹出
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardWillHideNotification object:nil]; // 键盘回收
    
}
#pragma mark ------------试图将要消失 界面消失时删除通知----------------
- (void)viewWillDisappear:(BOOL)animated
{   [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
   
}

- (void)getData:(NSInteger)number;
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    [RequestManger requestWithURL:[NSString stringWithFormat:@"http://www.xdmeishi.com/index.php?m=mobile&c=index&a=getComments&id=%@&pageNum=%ld&pageSize=15",_myID,number] requestType:@"RequestGet" parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        [_modelArray removeAllObjects];
        NSArray *array = dic[@"data"];
        if (array.count != 0) {
            for (NSDictionary *dic in array) {
                CommentModel *model = [[CommentModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                NSDictionary *useDic = dic[@"user"];
                [model setValuesForKeysWithDictionary:useDic];
                [_modelArray addObject:model];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    } error:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"所有评论";
    
    [self getData:1];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 1000;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"发表评论" style:UIBarButtonItemStylePlain target:self action:@selector(write:)];
    self.navigationItem.rightBarButtonItem = right;
    
    _keyview = [[UIView alloc]initWithFrame:CGRectMake(0, 300, Width, 40)];
    self.commentField = [[UITextField alloc]initWithFrame:CGRectMake(10, 5, Width - 20, 30)];
    self.commentField.delegate = self;
    //设置占位符
    self.commentField.placeholder = @"评论";
    //设置对齐方式
    self.commentField.textAlignment = NSTextAlignmentLeft;
    self.commentField.borderStyle = UITextBorderStyleRoundedRect;
    [_keyview addSubview:_commentField];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_modelArray.count == 0) {
        return 10;
    }
    else return _modelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"comment"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"CommentTableViewCell" owner:nil options:nil].firstObject;
    }
    if (_modelArray.count != 0) {
        CommentModel * model = _modelArray[indexPath.row];
         cell.model = model;
        [cell.remind addTarget:self action:@selector(remind:) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}
//举报
- (void)remind:(UIButton *)button
{
    UIAlertController *control = [UIAlertController alertControllerWithTitle:@"提示" message:@"举报成功" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [control addAction:cancelAction];
    [self presentViewController:control animated:YES completion:nil];
}
//发表评论
- (void)write:(UIBarButtonItem *)right
{
    //弹出键盘
    [_commentField becomeFirstResponder];
    [self.view addSubview:_keyview];
}
#pragma mark ---------键盘弹出的时候---------
- (void)keyBoardShow:(NSNotification *)notification
{
    NSDictionary *info = notification.userInfo;
    //拿到键盘弹出后的Frame
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize size = [value CGRectValue].size;
    _keyview.frame = CGRectMake(_keyview.frame.origin.x, Height - size.height - 40 - 64, _keyview.frame.size.width, 40);
    [self.view addSubview:_keyview];
}
#pragma mark -----------键盘回收的时候-----------
- (void)keyBoardHide:(NSNotification *)notification
{
    [_keyview removeFromSuperview];
}
#pragma mark ----------点击回收键盘-------------
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{   //取消第一响应者
    [textField resignFirstResponder];
    if(![[NSUserDefaults standardUserDefaults]boolForKey:@"loadState"])
    {
        UIAlertController *control = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [control addAction:cancelAction];
        [self presentViewController:control animated:YES completion:nil];
    }else
    {    NSString *string = _commentField.text;
        NSString *sessionid = [[NSUserDefaults standardUserDefaults]objectForKey:@"myid"];
        string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [RequestManger requestWithURL:[NSString stringWithFormat:@"http://www.xdmeishi.com/index.php?m=mobile&c=index&a=addComment&content=%@&id=%@&sessionId=%@",string,_myID,sessionid] requestType:@"RequestGet" parDic:nil finish:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
           // NSDictionary *dataDic = dic[@"data"];
            NSString *string = dic[@"description"];
            NSString *result = dic[@"result"];
            if ([result isEqualToString:@"ok"]) {
                string = @"发布成功";
                //发布成功后刷新界面
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self getData:1];
                });
                UIAlertController *control = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                [control addAction:cancelAction];
                [self presentViewController:control animated:YES completion:nil];
            }
            
            NSLog(@"%@",dic);
        } error:nil];
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
